package com.minicat.server;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {
    private Socket socket;

    private Mapper mapper;

    public RequestProcessor(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try{
            System.out.println("当前线程是:"+Thread.currentThread().getName());
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            //封装Request对象和Response对象
            Request request = new Request(inputStream);
            System.out.println(request);
            Response response = new Response(outputStream);
            Servlet servlet = null;
            //静态资源处理
            for (Host host : mapper.getHosts()) {
                if (host.getName().equalsIgnoreCase(request.getHost())){
                    for (Context context : host.getContexts()) {
                        for (Wrapper wrapper : context.getWrappers()) {
                            if (wrapper.getServletMap().containsKey(request.getUrl())){
                                servlet = wrapper.getServletMap().get(request.getUrl());
                                break;
                            }
                        }
                    }
                }
            }
            //静态资源
            if (servlet == null){
                response.outputHtml(request,mapper);
            } else {
                servlet.service(request,response);
            }
            socket.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
